package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.itheima.bean.*;
import com.itheima.mapper.AddressBoosMapper;
import com.itheima.mapper.OrderDetailMapper;
import com.itheima.mapper.OrderMapper;
import com.itheima.mapper.ShoppingCartMapper;
import com.itheima.service.OrderService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

@Service
@Transactional
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper om;

    @Autowired
    private AddressBoosMapper am;

    @Autowired
    private ShoppingCartMapper sm;

    @Autowired
    private OrderDetailMapper odm;

    /**
     * 添加订单
     * 1、往那些表添加数据
     * 1.1 提交订单就是要往两张条添加记录，order表 order_detail表
     * 1.2 先考虑往order表添加数据，然后再考虑往order_detail表添加记录
     * 2、先添加order表
     * <p>
     * 3、再添加order_detail表
     *
     * @param orders
     * @return
     */
    @Override
    public int add(Orders orders, User user) {

        //1、往订单表添加数据
        // 根据地质id来查询地址信息
        AddressBook addressBook = am.selectById(orders.getAddressBookId());

        //1.1 补充user信息
        // 订单号
        orders.setNumber(UUID.randomUUID().toString().replace("-", ""));
        // 状态
        orders.setStatus(1);
        // 下单用户id
        orders.setUserId(user.getId());
        // 地址id值, 不需要设置，页面已经提交上来了

        // 付款时间
        orders.setOrderTime(LocalDateTime.now());
        // 支付方式 1：微信 ， 2：支付宝
        orders.setCheckoutTime(LocalDateTime.now());
        // 总金额 ,  不需要设置，页面已经提交上来了
        // 备注 ,    不需要设置，页面已经提交上来了

        // 收货人的电话
        orders.setPhone(addressBook.getPhone());
        // 收货人的地址
        String address = (addressBook.getProvinceName() != null ? addressBook.getProvinceName() : "") +
                         (addressBook.getCityName() != null ? addressBook.getCityName() : "") +
                         (addressBook.getDistrictName() != null ? addressBook.getDistrictName() : "") +
                         (addressBook.getDetail() != null ? addressBook.getDetail() : "");
        orders.setAddress(address);
        // 下单人的昵称
        orders.setUserName(user.getName());
        // 收货人的名字
        orders.setConsignee(addressBook.getConsignee());

        //添加订单
        int row = om.insert(orders);
        int row2 = 0;
        List<ShoppingCart> cartList = null;
        /*
           2、添加订单详情
               2.1 订单详情是来自于购物车的数据
               2.2 购物车里面有3件菜品，那么就应该有3个订单详情记录
         */
        if (row > 0) {
            //2.1、获取购物车数据
            LambdaQueryWrapper<ShoppingCart> lqw = new LambdaQueryWrapper<>();
            lqw.eq(ShoppingCart::getUserId,user.getId());
            cartList = sm.selectList(lqw);
            //2.2、遍历购物车,遍历一次，就有一个OrderDetail对象
            for (ShoppingCart cart : cartList) {
                //2.3 构建OrderDetail，组装数据
                OrderDetail orderDetail = new OrderDetail();
                //IdWorker:MybatisPlus一个生成id的工具类
                orderDetail.setId(IdWorker.getId());
                /*//2.3.1 买的商品|菜品的名称
                orderDetail.setName(cart.getName());
                //2.3.2 图片
                orderDetail.setImage(cart.getImage());
                //2.3.3 订单id
                orderDetail.setOrderId(orders.getId()); //就这玩意儿不一样
                //2.3.4 菜品id
                orderDetail.setDishId(cart.getDishId());
                //2.3.5 套餐id
                orderDetail.setSetmealId(cart.getSetmealId());
                //2.3.6 菜品口味
                orderDetail.setDishFlavor(cart.getDishFlavor());
                //2.3.7 购买数量
                orderDetail.setNumber(cart.getNumber());
                //2.3.8 金额
                orderDetail.setAmount(cart.getAmount());*/
                //上面那个太麻烦了，我们来取巧
                BeanUtils.copyProperties(cart,orderDetail);
                orderDetail.setOrderId(orders.getId());

                //2.4 添加到订单详情表
                row2 += odm.insert(orderDetail);
            }
        }
        //下单成功了之后，就应该清空购物车
        if (row > 0 && row2 == cartList.size()){
            //清空购物车
            LambdaQueryWrapper<ShoppingCart> lqw = new LambdaQueryWrapper<>();
            lqw.eq(ShoppingCart::getUserId,user.getId());
            sm.delete(lqw);
            return 1;
        }


        //问题来了，返回值写啥？
        //return row > 0 && row2 == cartList.size() ? 1 : 0;
        return 0;
        //这里最后我们会有重复id，不知什么原因，清空购物车再重新添加又可以了
    }
}
